import { Form, Input, message, Modal, type FormProps } from "antd";
import { useEffect, useState, useRef } from "react";
import { addBuilding } from "../../apis/building";
import type { AddbuildingParams, editContentFace } from "../../type/building";

interface PropsParams {
    openAdd: boolean;
    refresh: () => void;
    editContent: editContentFace
}

type FieldType = {
    id?: number;
    name?: string;
    pid?:number
};

export default function AddDiaLog({ openAdd, refresh, editContent }: PropsParams) {
    const [isModalOpen, setIsModalOpen] = useState(openAdd);
    const formRef = useRef<any>(null); // 创建表单引用
    useEffect(() => {
        if (!isModalOpen) {
            // 当模态框关闭时，通知父组件更新状态
            // 这样可以确保下次打开时状态是同步的
            refresh();
        }
    }, [isModalOpen]);
    useEffect(() => {
    console.log(editContent.content);
    
    if (editContent.id) {
        // 使用 setTimeout 确保在下次渲染时表单已挂载
        setTimeout(() => {
            if (formRef.current) {
                // 将 editContent.content 字段内容填充到表单的 name 字段上
                formRef.current.setFieldsValue({ name: editContent.content });
                console.log(formRef.current.getFieldsValue());
            }
        }, 0);
    } else if (formRef.current) {
        // 延迟清空表单，确保表单已挂载
        setTimeout(() => {
            formRef.current?.resetFields(); // 清空表单
        }, 0);
    }
}, [editContent]);

    useEffect(() => {
        setIsModalOpen(openAdd);
    }, [openAdd]);

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        editContent.id ? edit(values) : Add(values)
    };
    const edit = async (values: FieldType) => {
        console.log(editContent);
        
        values.id = editContent.id
        values.pid = editContent.pid
        console.log(values);
        
        let res = await addBuilding(values as AddbuildingParams)
        if (res.errCode == 10000) {
            message.success('修改成功');
            refresh()
            formRef.current?.resetFields(); // 清空表单数据
        } else {
            message.error('修改失败');
        }
        setIsModalOpen(false);
    };
    const Add = async (values: FieldType) => {
        values.id = 0
        let res = await addBuilding(values as AddbuildingParams)
        if (res.errCode == 10000) {

            message.success('添加成功');
            refresh()
            formRef.current?.resetFields(); // 清空表单数据
        } else {
            message.error('添加失败');
        }
        setIsModalOpen(false);
    }

    const handleOk = () => {
        formRef.current?.submit(); // 触发表单提交
    };

    return (
        <Modal
            title={editContent.id ? '修改节点' : '添加节点'}
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}  // 使用 handleOk 替代 onFinish
            onCancel={handleCancel}
            okText="确认"
            cancelText="取消"
        >
            <Form
                ref={formRef}  // 绑定表单引用
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="名称"
                    name="name"
                    rules={[{ required: true, message: '请输入小区名称' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    );
}